package com.zhongshengnetwork.rightbe.lang.view;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
//import android.support.v4.app.ActivityCompat;
//import android.support.v4.content.ContextCompat;
//import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.hys.utils.ImageUtils;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.gsonmodel.SignDataModel;
import com.zhongshengnetwork.rightbe.imageviewer.ViewData;
import com.zhongshengnetwork.rightbe.imageviewer.widget.ImageViewer;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.wang.avi.AVLoadingIndicatorView;
import com.yalantis.ucrop.UCrop;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.LetterConstant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.QiniuCallBack;
import com.zhongshengnetwork.rightbe.common.QiniuUploadModel;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbmodel.LetterdbModel;
import com.zhongshengnetwork.rightbe.dbservice.LetterdbService;
import com.zhongshengnetwork.rightbe.dbservice.LogindbService;
import com.zhongshengnetwork.rightbe.gsonmodel.CircleLangModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.QiniuModel;
import com.zhongshengnetwork.rightbe.gsonmodel.UserInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.UserSignModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.ReadInfoActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SelfImagePreviewActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SignGoalActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SignShareActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SmartRankActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SmartRankSettingsActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SmartRankShareActivity;
import com.zhongshengnetwork.rightbe.letter.activity.ChatViewActivity;
import com.zhongshengnetwork.rightbe.letter.activity.LetterSettingActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.my.activity.EditActivity;
import com.zhongshengnetwork.rightbe.my.activity.MyAreaActivity;
import com.zhongshengnetwork.rightbe.my.activity.SettingsActivity;
import com.zhongshengnetwork.rightbe.qrcode.QRCodeActivity;
import com.zhongshengnetwork.rightbe.wzt.view.GlideEngine;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import me.iwf.photopicker.PhotoPicker;
//import me.iwf.photopicker.PhotoPickerActivity;
//import me.iwf.photopicker.utils.PhotoPickerIntent;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * Created by luojingxing on 2018/6/17.
 */

public class UserFragment extends BaseAnalyticsFragment {
    public String userid = null;
    private View rootView;//缓存Fragment view

    private static final int TAKE_PICTURE = 1000;//拍照
    private static final int CHOOSE_PICTURE = 1001;//从相册选
    private static final int SELECT_LOCATION = 10002;//选择了位置
    private static final int REQUEST_PERMISSION = 10003;
    private static final int CROP_PICTURE = 1003;//裁剪图片
    private static final int SCALE = 5;
    public static final int NICKNAME_REQUSET = 1004;//昵称
    public static final int SIGN_REQUEST = 1005;//签名
    private static final int PHOTO_PICKER_REQUEST_CODE = 10004; //android 13从相册选择一张图片
    private List<String> list=null;
    private List<String> groupkey=new ArrayList<String>();
    private ListView listview;
    //private PublishSelectPicPopupWindow menuWindow;
    private List<String> itemList;
    private int imgType = 0;
    private MyAdapter adapter;
    private List<String> names;
    private UserInfoModel userInfoModel = null;
    private CircleLangModel circleLangModel = null;
    private TextView myinfo_sigin;
    private TextView myinfo_letter;
    private LinearLayout read_time_layout;
    private TextView read_time;
    private TextView smart_rank;
    //加载动画
    private AVLoadingIndicatorView avi;
    private int imgW = 0;
    private int imgH = 0;

    //图片浏览
    public ImageViewer imagePreivew;
    List<ViewData> mViewDatas = new ArrayList<ViewData>();
    List<Object> mImageList = new ArrayList<Object>();
    private float density = 0;
    private int signtime = 0;
    private UserSignModel userSignModel = null;
    private List<String> nameList;

    private ClipboardManager myClipboard;

    public boolean loaded = false;

    private void calculateImageWidth(){
        density = ScreenUtils.getScreenDensity(CustomApplication.mContext);
        imgW = ScreenUtils.getScreenWidth(CustomApplication.mContext);
        imgH = (int) (imgW*10.0f/16.0f);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        calculateImageWidth();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        loaded = false;
        if (rootView == null){
            rootView = inflater.inflate(R.layout.user_fragment_layout, container,false);
            smart_rank = (TextView) rootView.findViewById(R.id.smart_rank);
            smart_rank.setClickable(true);
            smart_rank.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (getActivity() == null){
                        return;
                    }

                    if (CommonUtils.isLogin() == false){
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }

                    boolean enable = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.Smart_Rank_State, false);
                    if (enable == true){
                        Intent intent = new Intent(getActivity(), SmartRankActivity.class);
                        startActivity(intent);
                    }else {
                        Intent intent = new Intent(getActivity(), SmartRankSettingsActivity.class);
                        startActivity(intent);
                    }
                }
            });
            read_time_layout = (LinearLayout) rootView.findViewById(R.id.read_time_layout);
            read_time = (TextView) rootView.findViewById(R.id.read_time);
            myinfo_sigin = (TextView) rootView.findViewById(R.id.myinfo_sigin);
            myinfo_letter = (TextView) rootView.findViewById(R.id.myinfo_letter);
            if (CommonUtils.isEmpty(userid)){
                myinfo_sigin.setVisibility(View.VISIBLE);
                myinfo_sigin.setClickable(true);
                myinfo_sigin.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.e("TAG","点击了签到");
                        userSign();
                    }
                });
                updateSignText();
                smart_rank.setVisibility(View.VISIBLE);
                read_time_layout.setVisibility(View.VISIBLE);
                read_time_layout.setClickable(true);
                read_time_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.e("TAG","点击了阅读");
                        userRead();
                    }
                });
                updateReadTimeText();
            }else {
                myinfo_sigin.setText("私信Ta");
                myinfo_sigin.setVisibility(View.VISIBLE);
                myinfo_sigin.setClickable(true);
                myinfo_sigin.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.e("TAG","点击了私信");
                        clickSX();
                    }
                });
                if (CommonUtils.isLogin() && userid.equals(CustomApplication.loginModel.getUid())){
                    myinfo_sigin.setVisibility(View.INVISIBLE);
                }
            }
            imagePreivew = (ImageViewer) rootView.findViewById(R.id.imagePreivew);
            density = ScreenUtils.getScreenDensity(CustomApplication.mContext);
            imgW = ScreenUtils.getScreenWidth(CustomApplication.mContext);
            imgH = (int) (imgW*10.0f/16.0f);
            avi = (AVLoadingIndicatorView)rootView.findViewById(R.id.avi);

            getData();
            listview = (ListView) rootView.findViewById(R.id.myinfo_listview);
            adapter=new MyAdapter();
            listview.setAdapter(adapter);
            RelativeLayout user_layout = (RelativeLayout) rootView.findViewById(R.id.user_layout);
            user_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
            listview.setDivider(new ColorDrawable(AppThemeUtils.getInstance().getBackgroundColor()));
            listview.setDividerHeight(ScreenUtils.dip2px(getActivity(), 1));
            getUserInfo();
            loaded = true;
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
            loaded = true;
        }

        myClipboard = (ClipboardManager)getActivity().getSystemService(CLIPBOARD_SERVICE);

        return rootView;
    }

    public void updateUserInfo(){
        if (adapter != null){
            getData();
            if (CommonUtils.isEmpty(userid) && CommonUtils.isLogin()){// && CommonUtils.isEmpty(CustomApplication.loginModel.getWeiJuId())
                getUserInfo();
            }
            adapter.notifyDataSetChanged();
        }
    }

    public void updateReadTimeText(){

        Log.e("TAG","阅读时长更新1");
        if (getActivity() == null  || CommonUtils.isLogin() == false){
            return;
        }
        Log.e("TAG","阅读时长2");
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (read_time == null){
                    if (rootView != null){
                        read_time = (TextView) rootView.findViewById(R.id.read_time);
                    }
                }
                Log.e("TAG","阅读时长3");
                if (read_time == null){
                    return;
                }
                Log.e("TAG","阅读时长4");
                int time = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.ReadTimeKey+CustomApplication.loginModel.getUid(),0);
                if (time == 0){
                    time = 1;
                }
                read_time.setText(time+"分钟");
            }
        });

    }

    //点击了私信
    private void clickSX(){
        if (getActivity() == null){
            return;
        }

        //是否登录
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            return;
        }

        //是否开通私信
        if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(LetterConstant.SXStateKey, false) == false){
            Intent intent = new Intent(getActivity(), LetterSettingActivity.class);
            startActivity(intent);
            return;
        }

        //是否可以通信
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("userid", userid);
        String url = "miniapp/letter/"+"langappid"+"/authority.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    LetterdbModel model = new LetterdbModel();
                    model.setUserid(CustomApplication.loginModel.getUid());
                    model.setFromuserid(userid);
                    model.setNickname(userInfoModel.getNickname());
                    model.setHeader(userInfoModel.getHeader());
                    int unReadCount = LetterdbService.getChatUnReadCount(model.getUserid(), model.getFromuserid());
                    model.setUnReadCount(unReadCount);
                    Intent intent = new Intent(getActivity(), ChatViewActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("model", model);//序列化
                    bundle.putInt("newCount",model.getUnReadCount());
                    intent.putExtras(bundle);//发送数据
                    startActivity(intent);
                    LetterdbService.changeToReadState(model.getUserid(), model.getFromuserid());
                }else {
                    if (commonModel.getCode().equals(Constant.UserReturnCode.CODE_10011)) {//登录过期
                        CustomApplication.showTip(commonModel, getActivity());
                        return;
                    }
                    ToastUtil.show(getActivity(), commonModel.getMsg());
                }
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(getActivity(), "网络繁忙，请稍后再试");
            }
        });

    }

    public void updateSignText(){
        Log.e("TAG","更新签到字眼");
        if (getActivity() == null || myinfo_sigin == null || CommonUtils.isLogin() == false){
            return;
        }
        if (CommonUtils.isLogin() == true && adapter != null && circleLangModel != null && CommonUtils.isEmpty(circleLangModel.getSign())){
            String level = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.UserLevelNameData+CustomApplication.loginModel.getUid(),"");
            if (!CommonUtils.isEmpty(level)){
                adapter.notifyDataSetChanged();
            }
        }
        String tdata = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.UserSignTime+CommonUtils.formatString(CustomApplication.loginModel.getUid()),"");
        if (!CommonUtils.isEmpty(tdata)){
            if (CommonUtils.isToday(Long.valueOf(tdata))){
                myinfo_sigin.setText("已签到");
                return;
            }
        }
        myinfo_sigin.setText("签到");
    }

    private void userSign(){
        if (getActivity() == null || myinfo_sigin == null ||  CommonUtils.isLogin() == false){
            return;
        }

        String tdata = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.UserSignTime+CommonUtils.formatString(CustomApplication.loginModel.getUid()),"");
        if (!CommonUtils.isEmpty(tdata)){
            if (CommonUtils.isToday(Long.valueOf(tdata))){
                String signData = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.SignData, "");
                if (!CommonUtils.isEmpty(signData)){
                    SignDataModel signDataModel = GsonTools.getSignDataModel(signData);
                    if (signDataModel != null){
                        Intent intent = new Intent(getActivity(), SignGoalActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", signDataModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        startActivity(intent);
                    }
                }else {
                    ToastUtil.show(getActivity(),"今天你已签到");
                }
                return;
            }
        }
        signtime = (int)(System.currentTimeMillis()/1000);
        avi.show();
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey,CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        HttpsUtils.miniAppDo(map, "miniapp/langappid/usersign.do", new HttpCallBack() {
            @Override
            public void onSuccess(final String data) {
                if (getActivity() != null){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            avi.hide();
                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (commonModel.getFlag().equals("1")){
                                myinfo_sigin.setText("已签到");
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.SignData, data);
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.UserSignTime+CustomApplication.loginModel.getUid(),signtime+"");
                                userSignModel = GsonTools.getUserSignModel(data);
                                if (userSignModel != null){
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.NewMsgNotifyKey+CustomApplication.loginModel.getUid(), userSignModel.isUnRead());
                                    if (!CommonUtils.isEmpty(userSignModel.getShareUrl())){
                                        signSuccess();
                                    }else {
                                        ToastUtil.show(getActivity(),commonModel.getMsg());
                                    }
                                }else {
                                    ToastUtil.show(getActivity(),commonModel.getMsg());
                                }
                            }else {
                                if (commonModel.getCode().equals("1000000")){
                                    myinfo_sigin.setText("已签到");
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.SignData, data);
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.UserSignTime+CustomApplication.loginModel.getUid(),signtime+"");
                                }
                                ToastUtil.show(getActivity(),commonModel.getMsg());
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(String msg) {
                 if (getActivity() != null){
                     getActivity().runOnUiThread(new Runnable() {
                         @Override
                         public void run() {
                             avi.hide();
                         }
                     });
                 }
            }
        });
    }

    private void userRead(){
        if (getActivity() == null || read_time_layout == null ||  CommonUtils.isLogin() == false){
            return;
        }
        String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.UserReadData+CommonUtils.formatString(CustomApplication.loginModel.getUid()),"");
        if (!CommonUtils.isEmpty(data)){
            userSignModel = GsonTools.getUserSignModel(data);
            if (userSignModel != null){
                if (!CommonUtils.isEmpty(userSignModel.getShareUrl())){
                    readInfo();
                    //signSuccess();
                }
            }
        }else {
            int lastRecordTime = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.LastRecordTimeKey+CustomApplication.loginModel.getUid(),0);
            if (lastRecordTime == 0){
                //第一次记录
                SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.ReadTimeKey+CustomApplication.loginModel.getUid(),1);
                SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.LastRecordTimeKey+CustomApplication.loginModel.getUid(),(int)(System.currentTimeMillis()/1000));
            }else {
                //判断是否是是今天
                if (CommonUtils.isToday(lastRecordTime)){
                    //今天
                }else {
                    //非今天，清零
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.ReadTimeKey+CustomApplication.loginModel.getUid(),1);
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.LastRecordTimeKey+CustomApplication.loginModel.getUid(),(int)(System.currentTimeMillis()/1000));
                }
            }
            //5分钟上次一次服务器
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    final HashMap<String, String> map = new HashMap<String, String>();
                    map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                    map.put(APIKey.countKey,SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.ReadTimeKey+CustomApplication.loginModel.getUid(),0)+"");
                    String url = "miniapp/"+"langappid"+"/readcount.do";
                    HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            Log.e("TAG","阅读上传结果："+data);
                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (commonModel.getFlag().equals("1")){
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.UserReadData+CustomApplication.loginModel.getUid(),data);
                                userSignModel = GsonTools.getUserSignModel(data);
                                if (userSignModel != null){
                                    if (!CommonUtils.isEmpty(userSignModel.getShareUrl())){
                                        if (getActivity() != null){
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    readInfo();
                                                    //signSuccess();
                                                }
                                            });
                                        }
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(String msg) {

                        }
                    });
                }
            }.start();
        }
    }

    private void readInfo(){
        if (userSignModel != null){

            int time = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.ReadTimeKey+CustomApplication.loginModel.getUid(),0);
            if (time == 0){
                time = 1;
            }
            userSignModel.setTodayTime(time);

            Intent intent = new Intent(getActivity(), ReadInfoActivity.class);
            Bundle bundle=new Bundle();
            bundle.putSerializable("model", userSignModel);//序列化
            intent.putExtras(bundle);//发送数据
            startActivity(intent);
        }

    }

    private void signSuccess(){
        if (getActivity() == null){
            return;
        }

        if (nameList == null){
            nameList = new ArrayList<String>();
            nameList.add("分享给微信好友");
            nameList.add("分享到微信朋友圈");
            nameList.add("分享给QQ好友");
            nameList.add("分享到QQ空间");
            nameList.add("分享到微博");
            nameList.add("分享到微句");
        }
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
        builder.setTitle(userSignModel.getTitle());
        builder.setMessage(userSignModel.getContent());
        builder.setPositiveButton("分享", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, int which) {
                dialog.dismiss();

                String signData = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.SignData, "");
                if (!CommonUtils.isEmpty(signData)){
                    SignDataModel signDataModel = GsonTools.getSignDataModel(signData);
                    if (signDataModel != null){
                        Intent intent = new Intent(getActivity(), SignShareActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", signDataModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        startActivity(intent);
                        return;
                    }

                }

                ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                        .builder()
                        .setTitle("请选择")
                        .setCancelable(false)
                        .setCanceledOnTouchOutside(true);
                for (String s : nameList){
                    actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            if (which == 1){//String url,String title,String content
                                //分享给微信好友
                                shareToWX(1,userSignModel.getShareUrl(),userSignModel.getTitle(),userSignModel.getContent());
                            }else if (which == 2){
                                //分享到朋友圈
                                shareToWX(0,userSignModel.getShareUrl(),userSignModel.getContent(), userSignModel.getTitle());
                            }else if (which == 3){
                                //分享到qq
                                shareToQQ(0,"微句-言微句美，发现共鸣",userSignModel.getContent());
                            }else if (which == 4){
                                //qq空间
                                shareToQQ(0,"微句-言微句美，发现共鸣",userSignModel.getContent());
                            }else if (which == 5){
                                //微博
                                CustomApplication.WbShareType = 3;
                                CustomApplication.WbShareSourceId = "";
                                CustomApplication.WbShareText = userSignModel.getContent();
                                CustomApplication.WbShareActionUrl = userSignModel.getShareUrl();
                                Intent mIntent = new Intent(BroadcastDefine.WeiBo_Share_Action);
                                //发送广播
                                getActivity().sendBroadcast(mIntent);
                            }else if (which == 6){
                                Intent mIntent = new Intent(BroadcastDefine.Publish_Sign_Action);
                                mIntent.putExtra("signtext","【"+userSignModel.getTitle()+"】"+userSignModel.getContent());
                                //发送广播
                                getActivity().sendBroadcast(mIntent);
                            }
                        }
                    });
                }
                actionSheetDialog.show();
            }
        });
        builder.setNegativeButton("知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void onClickCopy(String text){
        if (getActivity() == null){
            return;
        }
        try{
            ClipData myClip = ClipData.newPlainText("text", text);
            myClipboard.setPrimaryClip(myClip);
            Toast.makeText(getActivity(), "微句ID已复制~",
                    Toast.LENGTH_SHORT).show();
        }catch (Exception e){

        }
    }

    //分享到微信
    private void shareToWX(int type,String url,String title,String content){
        //初始化一个WXWebpageObject对象，填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        //用WXWebpageObject对象初始化一个WXMediaMessage对象，填写标题、描述
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = content;
        Bitmap thumb = BitmapFactory.decodeResource(getResources(),R.mipmap.icon);
        msg.thumbData = CommonUtils.bitmapToByteArray(thumb,true);
        //构成一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }

    //分享到qq
    private Bundle params;
    private void shareToQQ(int type,String title,String content) {
        params = new Bundle();
        if (type == 0) {//分享给QQ好友
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, userSignModel.getShareUrl());// 内容地址
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, userSignModel.getShareIcon());// 网络图片地址
            params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQQ(getActivity(), params, null);
                }
            });
        } else {
            //分享到QQ空间
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, userSignModel.getShareUrl());// 内容地址
            ArrayList<String> imgUrlList = new ArrayList<>();
            imgUrlList.add(userSignModel.getShareIcon());
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imgUrlList);// 图片地址
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQzone(getActivity(), params, null);
                }
            });
        }
    }


    private void getData(){
        itemList = new ArrayList<String>();
        itemList.add("拍一张");
        itemList.add("从相册选");
        //itemList.add("取消");
        names = new ArrayList<String>();
        names.add("男");
        names.add("女");
        names.add("保密");
        //names.add("取消");

        list = new ArrayList<String>();
        groupkey.add("0组");
        list.add("0组");

        groupkey.add("A组");
        List<String> aList = new ArrayList<String>();
        aList.add("昵称");
        aList.add("性别");
        list.add("A组");
        list.addAll(aList);


        groupkey.add("B组");
        List<String> bList = new ArrayList<String>();
        bList.add("创作等级");
        bList.add("微句ID");
        if (CommonUtils.isEmpty(userid)){
           bList.add("私信");
        }
        bList.add("二维码");
        list.add("B组");
        list.addAll(bList);

        groupkey.add("C组");
        List<String> cList = new ArrayList<String>();
        cList.add("地区");
        cList.add("个性签名");
        if (CommonUtils.isEmpty(userid)){
            cList.add("开启夜间模式");
        }
        list.add("C组");
        list.addAll(cList);

        if (CommonUtils.isEmpty(userid)){
            userInfoModel = new UserInfoModel();
            userInfoModel.setBackground(CustomApplication.loginModel.getBackground());
            userInfoModel.setThumbheader(CustomApplication.loginModel.getHeader());
            userInfoModel.setNickname(CustomApplication.loginModel.getNickname());
            userInfoModel.setSex(CustomApplication.loginModel.getSex());
            userInfoModel.setLocation(CustomApplication.loginModel.getLocation());
            userInfoModel.setSignature(CustomApplication.loginModel.getSignature());
            userInfoModel.setWeiJuId(CommonUtils.formatString(CustomApplication.loginModel.getWeiJuId()));
        }else {
            userInfoModel = new UserInfoModel();
            userInfoModel.setBackground("");
            userInfoModel.setThumbheader("");
            userInfoModel.setNickname("");
            userInfoModel.setSex("");
            userInfoModel.setLocation("");
            userInfoModel.setSignature("");
            userInfoModel.setWeiJuId("");
        }
    }

    public void getUserInfo(){
        String uid = CustomApplication.loginModel.getUid();

        //判断获取时间
        boolean getInfo = false;
        if (CommonUtils.isEmpty(userid) && CommonUtils.isLogin() == true && loaded == true){
            int lastTime = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.GetMyInfoKey, 0);
            if ((int)(System.currentTimeMillis()/1000) - lastTime > 30){
                SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.GetMyInfoKey, (int)(System.currentTimeMillis()/1000));
                getInfo = true;
            }
        }

         if (!CommonUtils.isEmpty(userid) || CommonUtils.isEmpty(CustomApplication.loginModel.getWeiJuId())){
             if (!CommonUtils.isEmpty(userid)){
                 uid = userid;
             }
             avi.show();
             new Thread(){
                 @Override
                 public void run() {
                     super.run();
                     final Map<String,String> map = new HashMap<String, String>();
                     map.put(APIKey.useridKey,userid);
                     map.put(APIKey.tokenKey,CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                     HttpsUtils.getUserInfoDo(map, new HttpCallBack() {
                         @Override
                         public void onSuccess(String data) {
                             if (getActivity() != null){
                                 getActivity().runOnUiThread(new Runnable() {
                                     @Override
                                     public void run() {
                                         avi.hide();
                                         CommonModel commonModel = GsonTools.getCommonModel(data);
                                         if (commonModel.getFlag().equals("1")){
                                             userInfoModel = GsonTools.getUserInfoModel(data);
                                             userInfoModel.setThumbheader(userInfoModel.getHeader());
                                             if (CommonUtils.isLogin() && CustomApplication.loginModel.getUid().equals(userid)){
                                                 CustomApplication.loginModel.setWeiJuId(userInfoModel.getWeiJuId());
                                             }
                                             adapter.notifyDataSetChanged();
                                         }
                                     }
                                 });
                             }
                         }

                         @Override
                         public void onError(String msg) {
                             if (getActivity() != null){
                                 getActivity().runOnUiThread(new Runnable() {
                                     @Override
                                     public void run() {
                                         avi.hide();
                                     }
                                 });
                             }
                         }
                     });
                 }
             }.start();
         }

         if (CommonUtils.isEmpty(userid) && loaded == true){
             if (getInfo == false){//不频繁请求服务器
                 return;
             }else {
                 SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.GetMyInfoKey, (int)(System.currentTimeMillis()/1000));
             }
         }

         final String otherUserId = uid;
         new Thread(){
             @Override
             public void run() {
                 super.run();
                 final Map<String,String> map = new HashMap<String, String>();
                 map.put(APIKey.useridKey,otherUserId);
                 HttpsUtils.miniAppDo(map, "miniapp/langappid/getusersimplelanginfo.do", new HttpCallBack() {
                     @Override
                     public void onSuccess(String data) {
                         CommonModel commonModel = GsonTools.getCommonModel(data);
                         if (commonModel.getFlag().equals("1")){
                             circleLangModel = GsonTools.getUserLangSimpleModel(data);
                             if (CommonUtils.isEmpty(circleLangModel.getUserid())){
                                 circleLangModel.setUserid("");
                             }
                             if (CommonUtils.isLogin() == true){
                                 if (circleLangModel.getUserid().equals(CustomApplication.loginModel.getUid())){
                                     SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.UserLevelNameData+CustomApplication.loginModel.getUid(), CommonUtils.formatString(circleLangModel.getSign()));
                                 }
                             }
                             if (getActivity() != null){
                                 getActivity().runOnUiThread(new Runnable() {
                                     @Override
                                     public void run() {
                                         adapter.notifyDataSetChanged();
                                     }
                                 });
                             }
                         }
                     }

                     @Override
                     public void onError(String msg) {

                     }
                 });
             }
         }.start();

    }

    private class MyAdapter extends BaseAdapter implements View.OnClickListener {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            if(groupkey.contains(getItem(position))){
                return false;
            }
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View view=convertView;
            if(groupkey.contains(getItem(position))){
                if (position == 0){
                    view= LayoutInflater.from(CustomApplication.mContext).inflate(R.layout.my_info_list_header, null);

                    RelativeLayout my_info_header_layout = (RelativeLayout) view.findViewById(R.id.my_info_header_layout);
                    my_info_header_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

                    ImageView myInfoBg = (ImageView) view.findViewById(R.id.my_info_bg);
                    ImageView myInfoHeader = (ImageView) view.findViewById(R.id.my_info_header);
                    ImageView privateIcon = (ImageView) view.findViewById(R.id.my_private_icon);
                    ViewGroup.LayoutParams params = myInfoBg.getLayoutParams();
                    params.width =imgW;
                    params.height = imgH;
                    myInfoBg.setLayoutParams(params);
                    //TextView my_info_detail = (TextView) view.findViewById(R.id.my_info_detail);
                    TextView smartVal = (TextView) view.findViewById(R.id.smartVal);
                    TextView bixinVal = (TextView) view.findViewById(R.id.bixinVal);
                    TextView weijuVal = (TextView) view.findViewById(R.id.weijuVal);
                    TextView commentVal = (TextView) view.findViewById(R.id.commentVal);
                    TextView fansVal = (TextView) view.findViewById(R.id.fansVal);
                    Glide.with(getActivity()).load(userInfoModel.getBackground()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(myInfoBg);
                    Glide.with(getActivity()).load(userInfoModel.getThumbheader()).transform(new CircleTransform(getActivity())).dontAnimate().into(myInfoHeader);
                    if (circleLangModel != null){
                        smartVal.setText(CommonUtils.getDisplayCount(circleLangModel.getLevel()));
                        bixinVal.setText(CommonUtils.getDisplayCount(circleLangModel.getLikecount()));
                        weijuVal.setText(CommonUtils.getDisplayCount(circleLangModel.getLangcount()-circleLangModel.getLifecount()));
                        commentVal.setText(CommonUtils.getDisplayCount(circleLangModel.getWeishucount()));
                        fansVal.setText(CommonUtils.getDisplayCount(circleLangModel.getFanscount()));

                        if (!CommonUtils.isEmpty(circleLangModel.getPrivateIcon())){
                            privateIcon.setVisibility(View.VISIBLE);
                            Glide.with(getActivity()).load(circleLangModel.getPrivateIcon()).transform(new CircleTransform(getActivity())).dontAnimate().into(privateIcon);
                        }else {
                            privateIcon.setVisibility(View.GONE);
                        }
                        //my_info_detail.setText("智慧值:"+CommonUtils.getDisplayCount(circleLangModel.getLevel())+"   微句:"+CommonUtils.getDisplayCount(circleLangModel.getLangcount())+"   评论:"+CommonUtils.getDisplayCount(circleLangModel.getCommentcount())+"   粉丝:"+CommonUtils.getDisplayCount(circleLangModel.getFanscount()));
                    }
                    myInfoBg.setOnClickListener(this);
                    myInfoHeader.setOnClickListener(this);
                    privateIcon.setOnClickListener(this);
                }else {
                    view= LayoutInflater.from(CustomApplication.mContext).inflate(R.layout.my_list_heaer, null);
                    LinearLayout my_list_header_line = (LinearLayout) view.findViewById(R.id.my_list_header_line);
                    my_list_header_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
                    TextView text = (TextView) view.findViewById(R.id.my_list_header_text);
                    text.setText("");
                }
            }else{
                view=LayoutInflater.from(CustomApplication.mContext).inflate(R.layout.my_info_list_item, null);
                TextView text = (TextView) view.findViewById(R.id.my_info_list_text);
                TextView detail = (TextView) view.findViewById(R.id.my_info_list_detail);
                TextView fullText = (TextView) view.findViewById(R.id.my_info_list_fulltext);
                ImageView next = (ImageView) view.findViewById(R.id.my_info_list_next);
                ImageView code = (ImageView) view.findViewById(R.id.my_info_list_code);
                ImageView theme_mode = (ImageView) view.findViewById(R.id.theme_mode);
                theme_mode.setVisibility(View.INVISIBLE);

                RelativeLayout my_info_item = (RelativeLayout) view.findViewById(R.id.my_info_item);
                my_info_item.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
                text.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
                detail.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
                fullText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

                if (!CommonUtils.isEmpty(userid)){
                    next.setVisibility(View.INVISIBLE);
                }
                text.setText((CharSequence) getItem(position));
                if (position == 2){//昵称
                    code.setVisibility(View.INVISIBLE);
                    detail.setText((CharSequence) userInfoModel.getNickname());
                }else if (position == 3){//性别
                    code.setVisibility(View.INVISIBLE);
                    if (userInfoModel.getSex().equals("0")){
                        detail.setText("保密");
                    }else if(userInfoModel.getSex().equals("1")){
                        detail.setText("男");
                    }else if(userInfoModel.getSex().equals("2")){
                        detail.setText("女");
                    }else {
                        detail.setText("");
                    }

                }else if(position == 5){//创作等级
                    next.setVisibility(View.VISIBLE);
                    code.setVisibility(View.INVISIBLE);
                    if (circleLangModel != null){
                        if (CommonUtils.isEmpty(circleLangModel.getSign())){
                            detail.setText("无");
                            if (CommonUtils.isLogin() == true){
                                if (circleLangModel.getUserid().equals(CustomApplication.loginModel.getUid())){
                                    detail.setText(SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.UserLevelNameData+CustomApplication.loginModel.getUid(),"无"));
                                }
                            }
                        }else {
                            detail.setText(circleLangModel.getSign());
                        }
                    }else {
                        detail.setText("");
                    }
                } else if (position == 6){//微句ID
                    next.setVisibility(View.VISIBLE);
                    code.setVisibility(View.INVISIBLE);
                    detail.setText((CharSequence) CommonUtils.formatString(userInfoModel.getWeiJuId()));
                }else if (position == 7){
                    if (CommonUtils.isEmpty(userid)){
                        //私信
                        code.setVisibility(View.INVISIBLE);
                        detail.setText("设置");
                    }else {
                        //二维码
                        code.setVisibility(View.VISIBLE);
                        detail.setText("");
                        next.setVisibility(View.VISIBLE);
                    }
                }else if (position == 8){
                    if (CommonUtils.isEmpty(userid)){
                        //二维码
                        code.setVisibility(View.VISIBLE);
                        detail.setText("");
                    }else {
                        code.setVisibility(View.INVISIBLE);
                        detail.setText("");
                    }
                }else if (position == 9){
                    if (!CommonUtils.isEmpty(userid)){
                        //地区
                        code.setVisibility(View.INVISIBLE);
                        detail.setText((CharSequence) userInfoModel.getLocation());
                    }else {
                        code.setVisibility(View.INVISIBLE);
                        detail.setText("");
                    }
                } else if (position == 10){
                    if (CommonUtils.isEmpty(userid)){
                        //地区
                        code.setVisibility(View.INVISIBLE);
                        detail.setText((CharSequence) userInfoModel.getLocation());
                    }else {
                        //个性签名
                        code.setVisibility(View.INVISIBLE);
                        detail.setText((CharSequence) userInfoModel.getSignature());
                    }

                }else if (position == 11){
                    //个性签名
                    if (CommonUtils.isEmpty(userid)){
                        code.setVisibility(View.INVISIBLE);
                        detail.setText((CharSequence) userInfoModel.getSignature());
                    }else {
                        code.setVisibility(View.INVISIBLE);
                        detail.setText("");
                    }
                }else if (position == 12){
                    //夜间模式
                    code.setVisibility(View.INVISIBLE);
                    theme_mode.setVisibility(View.VISIBLE);
                    next.setVisibility(View.INVISIBLE);
                    detail.setText("");
                    int appTheme = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AppThemeUtils.AppThemeKey, AppThemeUtils.AppThemeConstant.NORMAL_APP_Theme);
                    if (appTheme == AppThemeUtils.AppThemeConstant.NIGHT_APP_Theme){
                       theme_mode.setImageResource(R.drawable.ios7_switch_on);
                    }else {
                        theme_mode.setImageResource(R.drawable.ios7_switch_off);
                    }
                }
                fullText.setTag(position);
                fullText.setOnClickListener(this);
            }
            return view;
        }

        // 监听事件实现
        public void onClick(View v) {

            if (v.getId() == R.id.my_info_bg){
                if(!CommonUtils.isEmpty(userid)){
                    preViewImage(false, v);
                }else {
                    if (getActivity() == null || itemsOnClick == null || itemList == null){
                        return;
                    }
                    imgType = 0;

                    /*
                    //System.out.print("点击了背景图\n");
                    menuWindow = new PublishSelectPicPopupWindow(getActivity(),itemsOnClick,itemList);
                    // 显示窗口
                    menuWindow.showAtLocation(v,
                            Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    */
                    ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                            .builder()
                            .setTitle("请选择")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true);
                    for (String s : itemList){
                        actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (which > 0){
                                    if (which == 1){
                                        doTakePhoto();
                                    }else if (which == 2){
                                        doPickPhotoFromGallery();
                                    }
                                }
                            }
                        });
                    }
                    actionSheetDialog.show();

                }

            }else if (v.getId() == R.id.my_info_header || v.getId() == R.id.my_private_icon){
                if(!CommonUtils.isEmpty(userid)){
                    preViewImage(true, v);
                }else {
                    System.out.print("点击了头像\n");
                    if (getActivity() == null || itemsOnClick == null || itemList == null){
                        return;
                    }
                    imgType = 1;

                    ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                            .builder()
                            .setTitle("请选择")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true);
                    for (String s : itemList){
                        actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (which > 0){
                                    if (which == 1){
                                        doTakePhoto();
                                    }else if (which == 2){
                                        doPickPhotoFromGallery();
                                    }
                                }
                            }
                        });
                    }
                    actionSheetDialog.show();

                    /*
                    menuWindow = new PublishSelectPicPopupWindow(getActivity(),itemsOnClick,itemList);
                    // 显示窗口
                    menuWindow.showAtLocation(v,
                            Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    */
                }

            }else {

                int destination = (Integer) v.getTag();
                switch (destination) {
                    case 2://昵称
                        if (getActivity() == null ){
                            return;
                        }
                        if(!CommonUtils.isEmpty(userid)){
                            return;
                        }
                        Intent intent = new Intent(getActivity(),
                                EditActivity.class);
                        intent.putExtra("type",NICKNAME_REQUSET);
                        intent.putExtra("name",CustomApplication.loginModel.getNickname());
                        getActivity().startActivityForResult(intent, NICKNAME_REQUSET);
                        break;
                    case 3://性别
                        if (getActivity() == null || itemsOnClick == null || itemList == null){
                            return;
                        }
                        if(!CommonUtils.isEmpty(userid)){
                            return;
                        }
                        imgType = 3;

                        /*
                        menuWindow = new PublishSelectPicPopupWindow(getActivity(),itemsOnClick,names);
                        // 显示窗口
                        menuWindow.showAtLocation(v,
                                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                        */
                        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                                .builder()
                                .setTitle("请选择")
                                .setCancelable(false)
                                .setCanceledOnTouchOutside(true);
                        for (String s : names){
                            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                                @Override
                                public void onClick(int which) {
                                    if (which > 0){
                                        if (which == 1){
                                            changeUserInfo(1);
                                        }else if (which == 2){
                                            changeUserInfo(2);
                                        }else if (which == 3){
                                            changeUserInfo(0);
                                        }
                                    }
                                }
                            });
                        }
                        actionSheetDialog.show();

                        break;
                    case 5://创作等级
                        Intent wIntent = new Intent(getActivity(), MyWebActivity.class);
                        wIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/note.do");
                        startActivity(wIntent);
                        break;
                    case 6:
                        //微句ID
                        onClickCopy(CommonUtils.formatString(userInfoModel.getWeiJuId()));
                        break;
                    case 7:
                        if (CommonUtils.isEmpty(userid)){
                            //私信
                            Intent letterIntent = new Intent(getActivity(), LetterSettingActivity.class);
                            getActivity().startActivity(letterIntent);
                        }else {
                            //二维码
                            Intent qrcodeIntent = new Intent(getActivity(), QRCodeActivity.class);
                            qrcodeIntent.putExtra("id", userid);
                            qrcodeIntent.putExtra("header", userInfoModel.getThumbheader());
                            qrcodeIntent.putExtra("name", userInfoModel.getNickname());
                            qrcodeIntent.putExtra("content", "微句ID："+CommonUtils.formatString(userInfoModel.getWeiJuId()));
                            getActivity().startActivity(qrcodeIntent);
                        }
                        break;
                    case 8:
                        if (CommonUtils.isEmpty(userid)){
                            //二维码
                            Intent qrcodeIntent = new Intent(getActivity(), QRCodeActivity.class);
                            qrcodeIntent.putExtra("id", CustomApplication.loginModel.getUid());
                            qrcodeIntent.putExtra("header", userInfoModel.getThumbheader());
                            qrcodeIntent.putExtra("name", userInfoModel.getNickname());
                            qrcodeIntent.putExtra("content", "微句ID："+CommonUtils.formatString(userInfoModel.getWeiJuId()));
                            getActivity().startActivity(qrcodeIntent);
                        }
                        break;
                    case 9:
                        if (!CommonUtils.isEmpty(userid)){
                            //地区，忽略
                        }
                        break;
                    case 10:
                        if (!CommonUtils.isEmpty(userid)){
                            //个性签名，忽略
                        }else {
                            if (getActivity() == null){
                                return;
                            }
                            PermissionUtils.isLocationNote(getActivity(), new PermissionCallback() {
                                @Override
                                public void onResult(boolean flag, boolean showAlert) {
                                    if (flag == true){
                                        getActivity().startActivityForResult(new Intent(getActivity(), MyAreaActivity.class),SELECT_LOCATION);
                                    }
                                }
                            });
                            break;
                        }
                        break;
                    case 11:
                        if (CommonUtils.isEmpty(userid)){
                            //个性签名
                            if (getActivity() == null){
                                return;
                            }
                            Intent signIntent = new Intent(getActivity(),
                                    EditActivity.class);
                            signIntent.putExtra("type",SIGN_REQUEST);
                            signIntent.putExtra("name", CommonUtils.formatString(CustomApplication.loginModel.getSignature()));
                            getActivity().startActivityForResult(signIntent, SIGN_REQUEST);
                        }
                        break;
                    case 12:
                        //夜间模式
                        showMode();
                        break;

                    default:
                        System.out.print("onClick\n");
                        break;
                }
            }

        }
    }

    private void showMode(){

        if (getActivity() == null){
            return;
        }

        //夜间模式
        String content = "";
        int appTheme = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AppThemeUtils.AppThemeKey, AppThemeUtils.AppThemeConstant.NORMAL_APP_Theme);
        if (appTheme == AppThemeUtils.AppThemeConstant.NIGHT_APP_Theme){
            appTheme = AppThemeUtils.AppThemeConstant.NORMAL_APP_Theme;
            content = "亲，应用当前已经开启夜间模式，如需关闭请按确定。";
        }else {
            appTheme = AppThemeUtils.AppThemeConstant.NIGHT_APP_Theme;
            content = "亲，应用当前已经关闭夜间模式，如需开启请按确定。";
        }
        final int nowAppTheme = appTheme;
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
        builder.setTitle("温馨提示");
        builder.setMessage(content);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AppThemeUtils.AppThemeKey, nowAppTheme);
                AppThemeUtils.getInstance().setAppTheme(nowAppTheme);
                //重启
                restartApplication();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void restartApplication() {

       final Intent intent = getActivity().getPackageManager().getLaunchIntentForPackage(getActivity().getPackageName());
       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
       startActivity(intent);

    }

    //预览图片
    private void preViewImage(final boolean isHeader, final View view){

          if (mImageList == null){
              return;
          }
          if(userInfoModel == null || CommonUtils.isEmpty(userInfoModel.getBackground()) || CommonUtils.isEmpty(userInfoModel.getHeader())){
              return;
          }
          if (getActivity() == null){
              return;
          }

        if (CustomApplication.isWatchingImg == true){
            return;
        }
        CustomApplication.isWatchingImg = true;

        int position = 0;
        Intent intent = new Intent(getActivity(), SelfImagePreviewActivity.class);
        intent.putExtra("position",position);
        intent.putExtra("isListImg",false);
        if (isHeader == true){
            intent.putExtra("imgH",imgW);
            intent.putExtra("imgs",userInfoModel.getHeader());
        }else {
            intent.putExtra("imgH",imgH);
            intent.putExtra("imgs",userInfoModel.getBackground());
        }
        //View代表方法传入的控件
        int[] viewLocation = new int[2];
        view.getLocationInWindow(viewLocation);
        int viewX = viewLocation[0]; // x 坐标
        int viewY = viewLocation[1]-(int) (20*ScreenUtils.getScreenDensity(CustomApplication.mContext))-(int) (90*density); // y 坐标，这里当顶部有状态栏时，要减去状态栏的高度
        intent.putExtra("viewX",viewX);
        intent.putExtra("viewY",viewY);
        intent.putExtra("imgW",imgW);
        getActivity().startActivity(intent);
        getActivity().overridePendingTransition(0,0);//可以通过参数设置关闭与要显示的动画效果,0表示无效果.

    }


    /**拍照获取相片**/
    private void doTakePhoto() {
        if (getActivity() == null){
            return;
        }

        PermissionUtils.showCamaraNote(getActivity(), new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (PermissionUtils.cameraIsCanUse() == true){
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));//Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
                        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        //直接使用，没有缩小
                        getActivity().startActivityForResult(intent, TAKE_PICTURE);  //用户点击了从相机获取
                    }else {
                        ActivityCompat.requestPermissions(getActivity(),
                                new String[]{Manifest.permission.CAMERA},
                                1);
                    }
                }
            }
        });

    }


    public static Uri getUriFromFile(Context context, File file) {
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context,
                    "com.zhongshengnetwork.rightbe.fileprovider", file);//通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }

    /**从相册获取图片**/
    private void doPickPhotoFromGallery() {
        if (getActivity() == null){
            return;
        }

        PermissionUtils.isPictureNote(getActivity(), new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                        startActivityForResult(intent, PHOTO_PICKER_REQUEST_CODE);
                        return;
                    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                            && ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                REQUEST_PERMISSION);
                        //ToastUtil.show(getActivity(),"亲，请开启应用对SD卡的读写权限");
                        return;
                    }

                    EasyPhotos.createAlbum(getActivity(), false, GlideEngine.getInstance())
                            .start(CHOOSE_PICTURE);
                }
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("TAG",resultCode+"UserFragment回调了："+requestCode+"\n");
        Uri imageUri = null;
        if (resultCode == RESULT_OK)
        {
            switch (requestCode) {
                case TAKE_PICTURE:
                    //cropImage(Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/image.jpg")));
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                        //5.0以下不裁剪
                        Bitmap bitmap = ImageUtils.getBitmap(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));
                        if (bitmap != null){
                            if (imgType == 0){//背景图
                                uploadBg(bitmap);
                            }else if (imgType == 1){//头像
                                uploadHeader(bitmap);
                            }
                        }
                    }else {
                        try {
                            imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));
                            if (imageUri == null){
                                return;
                            }
                            cropImage(imageUri);
                        }catch (Exception e){
                            ToastUtil.show(getActivity(),"亲，你这次没拍好哦，再来一次哟~");
                        }
                    }

                    break;
                case PHOTO_PICKER_REQUEST_CODE:
                    if (data != null){
                        cropImage(data.getData());
                    }
                    break;

                case CHOOSE_PICTURE:
                    if (data != null){
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                            //5.0以下不裁剪
                            try{
                                ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                                if (resultPhotos != null && resultPhotos.size() > 0){
                                    Photo photo = resultPhotos.get(0);
                                    Bitmap bitmap = ImageUtils.getBitmap(photo.path);
                                    if (bitmap != null){
                                        if (imgType == 0){//背景图
                                            uploadBg(bitmap);
                                        }else if (imgType == 1){//头像
                                            uploadHeader(bitmap);
                                        }
                                    }
                                }
                            }catch (Exception e){
                                ToastUtil.show(getActivity(), "亲，你选择的图片不可用，请选取其他图片试试哦");
                            }
                        }else {
                            try{
                                ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                                if (resultPhotos != null && resultPhotos.size() > 0){
                                    Photo photo = resultPhotos.get(0);
                                    imageUri = getUriFromFile(CustomApplication.mContext,new File(photo.path));
                                    cropImage(imageUri);
                                }
                            }catch (Exception e){
                                ToastUtil.show(getActivity(), "亲，你选择的图片不可用，请选取其他图片试试哦");
                            }
                        }
                    }
                    break;

                case CROP_PICTURE:
                    // 拿到剪切数据
                    if (data == null){
                        return;
                    }
                    Bitmap bmap = data.getParcelableExtra("data");
                    if (bmap != null){
                        if (imgType == 0){//背景图
                            uploadBg(bmap);
                        }else if (imgType == 1){//头像
                            uploadHeader(bmap);
                        }
                    }
                    break;

                case NICKNAME_REQUSET:
                    userInfoModel.setNickname(CustomApplication.loginModel.getNickname());
                    adapter.notifyDataSetChanged();
//                    Intent mIntent = new Intent(BroadcastDefine.Update_MyInfo);
//                    //发送广播
//                    sendBroadcast(mIntent);
                    break;

                case SIGN_REQUEST:
                    userInfoModel.setSignature(CustomApplication.loginModel.getSignature());
                    adapter.notifyDataSetChanged();
                    break;
                case SELECT_LOCATION:
                    userInfoModel.setLocation(CustomApplication.loginModel.getLocation());
                    adapter.notifyDataSetChanged();
                    break;

                case UCrop.REQUEST_CROP:
                    if (data == null){
                        return;
                    }
                    try {
                        final Uri resultUri = UCrop.getOutput(data);
                        Bitmap bitmap = BitmapFactory.decodeFile(resultUri.getEncodedPath());
                        if (imgType == 0){//背景图
                            uploadBg(bitmap);
                        }else if (imgType == 1){//头像
                            uploadHeader(bitmap);
                        }
                    }catch (Exception e){
                        ToastUtil.show(getActivity(), "亲，你选择的图片不可用，请选取其他图片试试哦");
                    }
                    break;

                default:
                    break;
            }
        }
    }

    /** 缩放Bitmap图片 **/
    public Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }

    /** 为图片创建不同的名称用于保存，避免覆盖 **/
    public static String createFileName() {
        String fileName = "";
        Date date = new Date(System.currentTimeMillis()); // 系统当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        fileName = dateFormat.format(date) + ".jpg";
        return fileName;
    }

    /**Save image to the SD card**/
    public static void savePhotoToSDCard(String path, String photoName,
                                         Bitmap photoBitmap) {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File photoFile = new File(path, photoName); //在指定路径下创建文件
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(photoFile);
                if (photoBitmap != null) {
                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,
                            fileOutputStream)) {
                        fileOutputStream.flush();
                    }
                }
            } catch (FileNotFoundException e) {
                photoFile.delete();
                e.printStackTrace();
            } catch (IOException e) {
                photoFile.delete();
                e.printStackTrace();
            } finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener(){

        public void onClick(View v) {
            //menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.first_button:
                    if (imgType == 3){
                        changeUserInfo(1);
                    }else {
                        doTakePhoto();
                    }

                    break;
                case R.id.second_button:
                    if (imgType == 3){
                        changeUserInfo(2);
                    }else {
                        doPickPhotoFromGallery();
                    }

                    break;
                case R.id.third_button:
                    if (imgType == 3){
                        changeUserInfo(0);
                    }
                    break;

                default:
                    imgType = 0;
                    break;
            }


        }

    };

    //裁剪
    private void cropImage(Uri uri){
        if (getActivity() == null){
            return;
        }
        float density = ScreenUtils.getScreenDensity(getActivity());
        if (imgType == 1){
            //头像
            UCrop.of(uri, Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),System.currentTimeMillis() + "imageout.jpg")))
                    .withAspectRatio(1, 1)
                    .withMaxResultSize((int)(1080*density), (int)(1080*density))
                    .start(getActivity(), this);
        }else {
            //背景图
            UCrop.of(uri, Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),System.currentTimeMillis() + "imageout.jpg")))
                    .withAspectRatio(16, 10)
                    .withMaxResultSize((int)(1080*density), (int)(675*density))
                    .start(getActivity(), this);
        }

    }

    //修改个人信息
    private void changeUserInfo(final int sexType){
        if (getActivity() == null){
            return;
        }
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put(APIKey.sexKey,sexType+"");
        HttpsUtils.changeuserinfoDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    userInfoModel.setSex(sexType+"");
                    CustomApplication.loginModel.setSex(sexType+"");
                    LogindbService.saveOrUpdateLogindbMode(CustomApplication.loginModel);
                    adapter.notifyDataSetChanged();
                }else {
                    CustomApplication.showTip(commonModel,getActivity());
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    //上传背景图片
    private void uploadBg(final Bitmap bitmap){
        if (getActivity() == null){
            return;
        }

        /*
        final CustomProgressDialog dialog = new CustomProgressDialog(getActivity(), "正在加载中",R.anim.frame);
        dialog.setmLoadingTip("正在上传...");
        dialog.show();
        */

        KyLoadingBuilder builder = new KyLoadingBuilder(getActivity());
        builder.setIcon(R.drawable.loading04);
        builder.setText("上传中...");
        builder.setOutsideTouchable(false);//点击空白区域是否关闭
        builder.setBackTouchable(true);//按返回键是否关闭
        builder.show();

        //将保存在本地的图片取出并缩小后显示在界面上
        //final Bitmap bitmap = zoomBitmap(ibitmap, ibitmap.getWidth() / SCALE, ibitmap.getHeight() / SCALE);
        //由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.getQiniuTokenDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")) {
                    final QiniuModel model = GsonTools.getQiniuModel(data);
                    final String name = System.currentTimeMillis()+"1"+".jpg";
                    CommonUtils.uploadBytesToQiniu(model.getUploadtoken(), model.getUploadurl(), name, CommonUtils.bitmapToBytes(bitmap), new QiniuCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            System.out.print("上传成功："+data+"\n");
                            if (data != null){
                                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                                    data += "-bg";
                                }
                                final String bg = data;
                                final Map<String,String> map = new HashMap<String, String>();
                                map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
                                map.put(APIKey.backgroundKey,data);
                                HttpsUtils.changeuserinfoDo(map, new HttpCallBack() {
                                    @Override
                                    public void onSuccess(String data) {
                                        if (getActivity() != null){
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    builder.dismiss();//关闭
                                                    CommonModel commonModel = GsonTools.getCommonModel(data);
                                                    if (commonModel.getFlag().equals("1")){
                                                        userInfoModel.setBackground(bg);
                                                        CustomApplication.loginModel.setBackground(bg);
                                                        LogindbService.saveOrUpdateLogindbMode(CustomApplication.loginModel);
                                                        adapter.notifyDataSetChanged();
                                                    }else {
                                                        CustomApplication.showTip(commonModel, getActivity());
                                                    }
                                                }
                                            });
                                        }
                                    }

                                    @Override
                                    public void onError(String msg) {
                                        if (getActivity() != null){
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    builder.dismiss();//关闭
                                                    ToastUtil.show(getActivity(),"上传失败");
                                                }
                                            });
                                        }
                                    }
                                });
                            }else {
                                if (getActivity() != null){
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            builder.dismiss();//关闭
                                            ToastUtil.show(getActivity(),"上传失败");
                                        }
                                    });
                                }
                            }
                        }

                        @Override
                        public void onModelSuccess(QiniuUploadModel data) {

                        }

                        @Override
                        public void onError(String msg) {
                            if (getActivity() != null){
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        builder.dismiss();//关闭
                                        ToastUtil.show(getActivity(),"上传失败");
                                    }
                                });
                            }
                        }
                    });
                }else {
                    if (getActivity() != null){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                builder.dismiss();//关闭
                                CustomApplication.showTip(commonModel,getActivity());
                            }
                        });
                    }
                }
            }

            @Override
            public void onError(String msg) {
                if (getActivity() != null){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            builder.dismiss();//关闭
                            ToastUtil.show(getActivity(),"上传失败");
                        }
                    });
                }
            }
        });
    }

    //上传头像
    private void uploadHeader(final Bitmap bitmap){
        if (getActivity() == null){
            return;
        }

        final Bitmap smallBitmap = ThumbnailUtils.extractThumbnail(bitmap,100,100);
        /*
        final CustomProgressDialog dialog = new CustomProgressDialog(getActivity(), "正在加载中",R.anim.frame);
        dialog.setmLoadingTip("正在上传...");
        dialog.show();
        */
        KyLoadingBuilder builder = new KyLoadingBuilder(getActivity());
        builder.setIcon(R.drawable.loading04);
        builder.setText("上传中...");
        builder.setOutsideTouchable(false);//点击空白区域是否关闭
        builder.setBackTouchable(true);//按返回键是否关闭
        builder.show();

        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.getQiniuTokenDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    final QiniuModel model = GsonTools.getQiniuModel(data);
                    long time = System.currentTimeMillis();
                    final String name = time+"1"+".jpg";
                    final String sname = time+"1s"+".jpg";
                    //上传大图
                    CommonUtils.uploadBytesToQiniu(model.getUploadtoken(), model.getUploadurl(), name, CommonUtils.bitmapToBytes(bitmap), new QiniuCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            System.out.print("大图上传成功："+data+"\n");
                            if (data != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                                data += "-square";
                            }
                            final String bUrl = data;
                            if (data != null){
                                //上传小图
                                CommonUtils.uploadBytesToQiniu(model.getUploadtoken(), model.getUploadurl(), sname, CommonUtils.bitmapToBytes(smallBitmap), new QiniuCallBack() {
                                    @Override
                                    public void onSuccess(String data) {
                                        System.out.print("小图上传成功："+data+"\n");
                                        if (data != null){
                                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                                                data += "-smallsquare";
                                            }
                                            final String sUrl = data;
                                            //上传到服务器
                                            final Map<String,String> map = new HashMap<String, String>();
                                            map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
                                            map.put(APIKey.headerKey,bUrl);
                                            map.put(APIKey.thumbheaderKey,sUrl);
                                            HttpsUtils.changeuserinfoDo(map, new HttpCallBack() {
                                                @Override
                                                public void onSuccess(String data) {
                                                    if (getActivity() != null){
                                                        getActivity().runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                builder.dismiss();
                                                                CommonModel commonModel = GsonTools.getCommonModel(data);
                                                                if (commonModel.getFlag().equals("1")){
                                                                    Log.e("TAG","图片上传成功\n");
                                                                    userInfoModel.setThumbheader(bUrl);
                                                                    userInfoModel.setHeader(bUrl);
                                                                    CustomApplication.loginModel.setHeader(bUrl);
                                                                    CustomApplication.loginModel.setThumbheader(sUrl);
                                                                    LogindbService.saveOrUpdateLogindbMode(CustomApplication.loginModel);
                                                                    adapter.notifyDataSetChanged();
//                                                        Intent mIntent = new Intent(BroadcastDefine.Update_MyInfo);
//                                                        //发送广播
//                                                        sendBroadcast(mIntent);
                                                                }else {
                                                                    ToastUtil.show(getActivity(),"上传失败");
                                                                }
                                                            }
                                                        });
                                                    }
                                                }

                                                @Override
                                                public void onError(String msg) {
                                                    if (getActivity() != null){
                                                        getActivity().runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                builder.dismiss();
                                                                ToastUtil.show(getActivity(),"上传失败");
                                                            }
                                                        });
                                                    }
                                                }
                                            });
                                            //上传到服务器
                                        }else {
                                            if (getActivity() != null){
                                                getActivity().runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        builder.dismiss();
                                                        ToastUtil.show(getActivity(),"上传失败");
                                                    }
                                                });
                                            }
                                        }
                                    }

                                    @Override
                                    public void onModelSuccess(QiniuUploadModel data) {

                                    }

                                    @Override
                                    public void onError(String msg) {
                                        if (getActivity() != null){
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    builder.dismiss();
                                                    ToastUtil.show(getActivity(),"上传失败");
                                                }
                                            });
                                        }
                                    }
                                });
                                //上传小图
                            }else {
                                if (getActivity() != null){
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            builder.dismiss();
                                            ToastUtil.show(getActivity(),"上传失败");
                                        }
                                    });
                                }
                            }
                        }

                        @Override
                        public void onModelSuccess(QiniuUploadModel data) {

                        }

                        @Override
                        public void onError(String msg) {
                            if (getActivity() != null){
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        builder.dismiss();
                                        ToastUtil.show(getActivity(),"上传失败");
                                    }
                                });
                            }
                        }
                    });
                    //上传图片
                }else {
                    if (getActivity() != null){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                builder.dismiss();
                                CustomApplication.showTip(commonModel,getActivity());
                            }
                        });
                    }
                }
            }

            @Override
            public void onError(String msg) {
                if (getActivity() != null){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            builder.dismiss();
                            ToastUtil.show(getActivity(),"上传失败");
                        }
                    });
                }
            }
        });
    }

}
